package cn.wsn2018.tools.service;

import cn.wsn2018.tools.common.CommonValue;
import cn.wsn2018.tools.dao.ProtocolDesignDao;
import cn.wsn2018.tools.dao.UserDao;
import cn.wsn2018.tools.model.Design.ProtocolDesign;
import cn.wsn2018.tools.model.User;
import cn.wsn2018.tools.model.VO.ProtocolDesignView;
import cn.wsn2018.tools.util.*;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.logging.Logger;
import java.util.regex.Pattern;

/**
 * 用于处理用户协议字段查询，协议字段设计的业务逻辑类
 */

@Service
public class ProtocolDesignService {

    @Autowired
    private ProtocolDesignDao protocolDesignDao;

    @Autowired
    private UserDao userDao;

    private Logger logger=Logger.getLogger(ProtocolDesignService.class.getName());

    /**
     * 新建协议设计
     * @param protocolDesign
     * @param myUsername
     * @return
     */
    public String dealProtocolDesignSave(ProtocolDesign protocolDesign,String myUsername,String token,HttpServletRequest request) throws Exception {
        //角色校验
        String res = RoleUtil.checkRole(token, request, CommonValue.ROLE_OPERATOR,CommonValue.OPERATOR_MODULE);
        if(!StringUtil.isEmptyString(res)){
            //如果结果字符串不为空，则表示角色校验失败，直接返回json字符串
            return res;
        }
        //由于之前的电科院 安全测试，使用抓包的方式可以篡改数据包，因此前端校验后，后端也要有对应的校验
        if(protocolDesign!=null){
            if(StringUtil.isEmptyString(protocolDesign.getDesignName())){
                //安全协议名为空
                LogUtil.produceLogs(myUsername,CommonValue.CREATE_TYPE,CommonValue.CREATE_DESIGN_LOGINFO,CommonValue.LOG_TYPE_BUS,CommonValue.FAILED);
                return JsonUtil.failedJson(CommonValue.JSON_INSERT_FAILED);
            }

            String regEx="[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
            Pattern pattern = Pattern.compile(regEx);
            if(pattern.matcher(protocolDesign.getDesignName()).find()){
                //协议名包含特殊字符
                LogUtil.produceLogs(myUsername,CommonValue.CREATE_TYPE,CommonValue.CREATE_DESIGN_LOGINFO,CommonValue.LOG_TYPE_BUS,CommonValue.FAILED);
                return JsonUtil.failedJson(CommonValue.JSON_INSERT_FAILED);
            }
            if(!StringUtil.isEmptyString(protocolDesign.getOther())){
                //备注包含特殊字符
                if(pattern.matcher(protocolDesign.getOther()).find()){
                    LogUtil.produceLogs(myUsername,CommonValue.CREATE_TYPE,CommonValue.CREATE_DESIGN_LOGINFO,CommonValue.LOG_TYPE_BUS,CommonValue.FAILED);
                    return JsonUtil.failedJson(CommonValue.JSON_INSERT_FAILED);
                }
            }

            if(protocolDesign.getDesignName().length()>10||protocolDesign.getOther().length()>20){
                //协议名或备注超过字数限制
                LogUtil.produceLogs(myUsername,CommonValue.CREATE_TYPE,CommonValue.CREATE_DESIGN_LOGINFO,CommonValue.LOG_TYPE_BUS,CommonValue.FAILED);
                return JsonUtil.failedJson(CommonValue.JSON_INSERT_FAILED);
            }

            //当前时间，以及进行时间格式化
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            sdf.setCalendar(new GregorianCalendar(new SimpleTimeZone(1000*60*60*8,"GMT")));

            //检测各个字段，发现特殊字符，去除后，再放回bean对象里面
            protocolDesign.setDesignName(Regex.checkReg(protocolDesign.getDesignName()));
            protocolDesign.setOther(Regex.checkReg(protocolDesign.getOther()));
            protocolDesign.setUsername(myUsername);
            protocolDesign.setCreateTime(sdf.format(date));

            //保存协议设计----调用dao层
            String id = protocolDesignDao.saveProtocolDesign(protocolDesign);
            //id不为null，表示保存成功
            if(id!=null){
                LogUtil.produceLogs(myUsername,CommonValue.CREATE_TYPE,CommonValue.CREATE_DESIGN_LOGINFO+",协议设计id为：D-"+(id.substring(6,8)+id.substring(18)).toUpperCase(),CommonValue.LOG_TYPE_BUS,CommonValue.SUCCESS);
                JSONObject objectId = new JSONObject();
                objectId.put("id",id);
                return JsonUtil.successJson(CommonValue.JSON_INSERT_SUCCESS,objectId,null);
            }else {
                //保存失败
                LogUtil.produceLogs(myUsername,CommonValue.CREATE_TYPE,CommonValue.CREATE_DESIGN_LOGINFO,CommonValue.LOG_TYPE_BUS,CommonValue.FAILED);
                return JsonUtil.failedJson(CommonValue.JSON_INSERT_FAILED);
            }
        }else {
            //protocolDesign对象没有数据，为null
            LogUtil.produceLogs(myUsername,CommonValue.CREATE_TYPE,CommonValue.CREATE_DESIGN_LOGINFO,CommonValue.LOG_TYPE_BUS,CommonValue.FAILED);
            return JsonUtil.failedJson(CommonValue.JSON_INPUT_ERROR);
        }

    }

    /**
     * 查询用户的全部协议设计
     * @param username
     * @return
     */
    public String dealProtocolDesignsQuery(String username,String pageNum,String pageSize,String token,HttpServletRequest request) throws Exception {
        //角色校验
        String res = RoleUtil.checkRole(token, request, CommonValue.ROLE_OPERATOR,CommonValue.  OPERATOR_MODULE);
        if(!StringUtil.isEmptyString(res)){
            //如果结果字符串不为空，则表示角色校验失败，直接返回json字符串
            return res;
        }

        if(username!=null&&!username.isEmpty()){
            User user = userDao.getUserByName(username);
            if(user!=null){
                List<ProtocolDesign> designs = protocolDesignDao.getProtocolDesigns(username,pageNum,pageSize);
                if(designs!=null){
                    List<ProtocolDesignView> result = new ArrayList<>();
                    for(ProtocolDesign protocolDesign : designs){
                        //ProtocolDesignView 返回给前端的数据对象类型，类似于视图
                        //ProtocolDesign 是数据库查出来自动注入的类型，可能含有敏感数据以及不想让前端知道的数据
                        ProtocolDesignView protocolDesignView = new ProtocolDesignView();
                        //注入各个属性
                        protocolDesignView.setId(protocolDesign.getId());
                        protocolDesignView.setUsername(protocolDesign.getUsername());
                        protocolDesignView.setProtocolName(protocolDesign.getProtocolName());
                        protocolDesignView.setDesignName(protocolDesign.getDesignName());
                        protocolDesignView.setCreateTime(protocolDesign.getCreateTime());
                        protocolDesignView.setOther(protocolDesign.getOther());
                        result.add(protocolDesignView);
                    }
                    //转换为json数组
                    JSONArray jsonArray = JSONArray.fromObject(result);
                    return JsonUtil.successJson(CommonValue.JSON_QUERY_SUCCESS,null,jsonArray);
                }else {
                    return JsonUtil.failedJson(CommonValue.JSON_QUERY_FAILED);
                }
            }else {
                return JsonUtil.failedJson(CommonValue.JSON_QUERY_FAILED);
            }
        }else {
            return JsonUtil.failedJson(CommonValue.JSON_INPUT_ERROR);
        }

    }


    /**
     * 查询某个设计
     * @param id
     * @return
     */
    public String dealProtocolDesignQuery(String id, String token, HttpServletRequest request) throws Exception {

        //角色校验
        String res = RoleUtil.checkRole(token, request, CommonValue.ROLE_OPERATOR,CommonValue.  OPERATOR_MODULE);
        if(!StringUtil.isEmptyString(res)){
            //如果结果字符串不为空，则表示角色校验失败，直接返回json字符串
            return res;
        }

        if(id!=null&&!id.isEmpty()){
            ProtocolDesign result = protocolDesignDao.getProtocolDesign(id);

            JSONObject jsonObject = JSONObject.fromObject(result);
            return JsonUtil.successJson(CommonValue.JSON_QUERY_SUCCESS,jsonObject,null);
        }else{
            return JsonUtil.failedJson(CommonValue.JSON_INPUT_ERROR);
        }
    }

    /**
     * 修改用户设计的字段信息
     * @param protocolDesign
     * @return
     */
    public String dealProtocolDesignUpdate(ProtocolDesign protocolDesign,String myUsername,String token,HttpServletRequest request) throws Exception {
        //角色校验
        String res = RoleUtil.checkRole(token, request, CommonValue.ROLE_OPERATOR,CommonValue.  OPERATOR_MODULE);
        if(!StringUtil.isEmptyString(res)){
            //如果结果字符串不为空，则表示角色校验失败，直接返回json字符串
            return res;
        }

        String id = protocolDesign.getId();
        if(protocolDesign!=null){
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            protocolDesign.setUsername(myUsername);
            //修改协议就不要重新设置它的创建时间了，但目前电科院测试没说啥，就还是保持原样吧
            protocolDesign.setCreateTime(sdf.format(date));
            boolean result = protocolDesignDao.updateProtocolDesign(protocolDesign);

            if(result){
                LogUtil.produceLogs(myUsername,CommonValue.UPDATE_TYPE,CommonValue.UPDATE_DESIGN_LOGINFO+"，协议设计id：D-"+(id.substring(6,8)+id.substring(18)).toUpperCase(),
                        CommonValue.LOG_TYPE_BUS,CommonValue.SUCCESS);
                return JsonUtil.successJson(CommonValue.JSON_UPDATE_SUCCESS,null,null);
            }else {
                LogUtil.produceLogs(myUsername,CommonValue.UPDATE_TYPE,CommonValue.UPDATE_DESIGN_LOGINFO+"，协议设计id：D-"+(id.substring(6,8)+id.substring(18)).toUpperCase(),CommonValue.LOG_TYPE_BUS,CommonValue.FAILED);
                return JsonUtil.failedJson(CommonValue.JSON_UPDATE_FAILED);
            }
        }else {
            LogUtil.produceLogs(myUsername,CommonValue.UPDATE_TYPE,CommonValue.UPDATE_DESIGN_LOGINFO+"，协议设计id：D-"+(id.substring(6,8)+id.substring(18)).toUpperCase(),CommonValue.LOG_TYPE_BUS,CommonValue.FAILED);
            return JsonUtil.failedJson(CommonValue.JSON_INPUT_ERROR);
        }

    }

    /**
     * 删除用户的某一协议设计
     */
    public String dealProtocolDesignDelete(String id,String myUsername,String token,HttpServletRequest request) throws Exception {
        //角色校验
        String res = RoleUtil.checkRole(token, request, CommonValue.ROLE_OPERATOR,CommonValue.  OPERATOR_MODULE);
        if(!StringUtil.isEmptyString(res)){
            //如果结果字符串不为空，则表示角色校验失败，直接返回json字符串
            return res;
        }

        if(id!=null&&!id.isEmpty()){
            boolean result = protocolDesignDao.deleteProtocolDesign(id);
            if(result){
                LogUtil.produceLogs(myUsername,CommonValue.DELETE_TYPE,CommonValue.DELETE_DESIGN_LOGINFO+"，协议设计id：D-"+(id.substring(6,8)+id.substring(18)).toUpperCase(),CommonValue.LOG_TYPE_BUS,CommonValue.SUCCESS);
                return JsonUtil.successJson(CommonValue.JSON_DELETE_SUCCESS, null,null);
            }else {
                LogUtil.produceLogs(myUsername,CommonValue.DELETE_TYPE,CommonValue.DELETE_DESIGN_LOGINFO+"，协议设计id：D-"+(id.substring(6,8)+id.substring(18)).toUpperCase(),CommonValue.LOG_TYPE_BUS,CommonValue.FAILED);
                return JsonUtil.failedJson(CommonValue.JSON_DELETE_FAILED);
            }
        }else {
            LogUtil.produceLogs(myUsername,CommonValue.DELETE_TYPE,CommonValue.DELETE_DESIGN_LOGINFO+"，协议设计id：D-"+(id.substring(6,8)+id.substring(18)).toUpperCase(),CommonValue.LOG_TYPE_BUS,CommonValue.FAILED);
            return JsonUtil.failedJson(CommonValue.JSON_INPUT_ERROR);
        }
    }

    /**
     * 批量删除协议设计
     * @param idList
     * @return
     */
    public String dealProtocolDesignsDelete(List<String> idList,String myUsername,String token,HttpServletRequest request) throws Exception {
        //角色校验
        String res = RoleUtil.checkRole(token, request, CommonValue.ROLE_OPERATOR,CommonValue.  OPERATOR_MODULE);
        if(!StringUtil.isEmptyString(res)){
            //如果结果字符串不为空，则表示角色校验失败，直接返回json字符串
            return res;
        }

        int num = idList.size();
        if(idList!=null&&num!=0){
            int count = protocolDesignDao.deleteProtocolDesigns(idList);
            if(count==num){
                LogUtil.produceLogs(myUsername,CommonValue.DELETE_TYPE,CommonValue.DELETE_DESIGN_LOGINFO+num+"条",CommonValue.LOG_TYPE_BUS,CommonValue.SUCCESS);
                return JsonUtil.successJson(CommonValue.JSON_DELETE_SUCCESS+",计划删除"+num+
                        "条,实际删除"+count+"条",null,null);
            }else {
                LogUtil.produceLogs(myUsername,CommonValue.DELETE_TYPE,CommonValue.DELETE_DESIGN_LOGINFO+num+"条",CommonValue.LOG_TYPE_BUS,CommonValue.FAILED);
                return JsonUtil.failedJson(CommonValue.JSON_DELETE_FAILED+",计划删除"+num+
                        "条,实际删除"+count+"条");
            }
        }else {
            LogUtil.produceLogs(myUsername,CommonValue.DELETE_TYPE,CommonValue.DELETE_DESIGN_LOGINFO+num+"条",CommonValue.LOG_TYPE_BUS,CommonValue.FAILED);
            return JsonUtil.failedJson(CommonValue.JSON_INPUT_ERROR);
        }
    }

    /**
     * 查询协议设计有哪些功能
     * @param id
     * @return
     */
    public String dealProtocolDesignFunctions(String id,String token,HttpServletRequest request) throws Exception {
        //角色校验
        String res = RoleUtil.checkRole(token, request, CommonValue.ROLE_OPERATOR,CommonValue.  OPERATOR_MODULE);
        if(!StringUtil.isEmptyString(res)){
            //如果结果字符串不为空，则表示角色校验失败，直接返回json字符串
            return res;
        }

        if(id!=null&&!id.isEmpty()){
            ProtocolDesign protocolDesign = protocolDesignDao.getProtocolDesign(id);
            if(protocolDesign!=null){
                List<String> funcList = new ArrayList<>();
                if(protocolDesign.getAuth()!=null){
                    funcList.add(CommonValue.FUNCTION_AUTHNEGO);
                }
                if(protocolDesign.getEncrypt()!=null){
                    funcList.add(CommonValue.FUNCTION_ENCRYPT);
                }
                if(protocolDesign.getException()!=null){
                    funcList.add(CommonValue.FUNCTION_EXCEPTION);
                }
                if(protocolDesign.getVirus()!=null){
                    funcList.add(CommonValue.FUNCTION_VIRUS);
                }
                if(protocolDesign.getResend()!=null){
                    funcList.add(CommonValue.FUNCTION_RESEND);
                }
                if(protocolDesign.getIntegrity()!=null){
                    funcList.add(CommonValue.FUNCTION_INTEGRITY);
                }
                JSONArray jsonArray = JSONArray.fromObject(funcList);
                return JsonUtil.successJson(CommonValue.JSON_QUERY_SUCCESS,null,jsonArray);
            }else {
                return JsonUtil.failedJson(CommonValue.JSON_QUERY_FAILED);
            }
        }else{
            return JsonUtil.failedJson(CommonValue.JSON_INPUT_ERROR);
        }
    }

}
